//
//  MXMobileLoginVC.m
//  HNBaseProject
//
//  Created by TR on 2024/6/4.
//

#import "MXMobileLoginVC.h"
#import "DCTabbarController.h"
#import "DCNavigationController.h"
#import "ExpandButton.h"
#import "AppDelegate.h"
#import "DCWebViewController.h"
@interface MXMobileLoginVC ()
{
    dispatch_source_t _timer;
}
@property(nonatomic,strong)UIButton                 *backBtn;//返回按钮
@property(nonatomic,strong)UILabel                  *titleLab;//标题

//手机号
@property(nonatomic,strong)UIImageView              *phoneIamgeV;
@property(nonatomic,strong)UITextField              *phoneTF;
@property(nonatomic,strong)UILabel                  *phoneLineLab;
//验证码
@property(nonatomic,strong)UIImageView              *codeIamgeV;
@property(nonatomic,strong)UITextField              *codeTF;
@property(nonatomic,strong)UIButton                 *codeBtn;//验证码
@property(nonatomic,strong)UILabel                  *codeLineLab;

@property(nonatomic,strong)UIButton                 *loginBtn;//登录
@property(nonatomic,strong)ExpandButton                 *choseBtn;//选择
@property(nonatomic,strong)YYLabel                  *choseLab;//阅读
@end

@implementation MXMobileLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backBtn setImage:[UIImage imageNamed:@"login_back"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
    
    self.titleLab = [[UILabel alloc]init];
    self.titleLab.text = @"手机验证码登录";
    self.titleLab.font = PFRFontMedium(21);
    self.titleLab.textColor = [UIColor colorWithHexString:@"#000000"];
    [self.view addSubview:self.titleLab];
    
    self.phoneIamgeV = [[UIImageView alloc]init];
    self.phoneIamgeV.image = [UIImage imageNamed:@"login_phone"];
    [self.view addSubview:self.phoneIamgeV];
    
    self.phoneTF = [[UITextField alloc]init];
    self.phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneTF.placeholder = @"请输入手机号码";
    self.phoneTF.textColor = [UIColor colorWithHexString:@"#000000"];
    self.phoneTF.font = PFRFontMedium(14);
    [self.view addSubview:self.phoneTF];
    [self.phoneTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    self.phoneLineLab = [[UILabel alloc]init];
    self.phoneLineLab.backgroundColor = [UIColor dc_colorWithHexString:@"#f5f5f5"];
    [self.view addSubview:self.phoneLineLab];
    
    self.codeIamgeV = [[UIImageView alloc]init];
    self.codeIamgeV.image = [UIImage imageNamed:@"login_code"];
    [self.view addSubview:self.codeIamgeV];
    
    self.codeTF = [[UITextField alloc]init];
    self.codeTF.placeholder = @"请输入短信验证码";
    self.codeTF.textColor = [UIColor colorWithHexString:@"#000000"];
    self.codeTF.font = PFRFontMedium(14);
    [self.codeTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:self.codeTF];
    
    self.loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginBtn.backgroundColor = [UIColor colorWithHexString:@"#E3E3E3"];
    self.loginBtn.userInteractionEnabled = NO;
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.layer.cornerRadius = 21;
    [self.loginBtn addTarget:self action:@selector(mobileLoginClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginBtn];
    
    self.codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.codeBtn setTitleColor:[UIColor colorWithHexString:@"#3378F7"] forState:UIControlStateNormal];
    self.codeBtn.titleLabel.font = PFRFontMedium(14);
    self.codeBtn.backgroundColor = [UIColor colorWithHexString:@"#f5f5f5"];
    self.codeBtn.layer.masksToBounds = YES;
    self.codeBtn.layer.cornerRadius = 14;
    [self.codeBtn addTarget:self action:@selector(codeClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.codeBtn];
    
    
    self.codeLineLab = [[UILabel alloc]init];
    self.codeLineLab.backgroundColor = [UIColor dc_colorWithHexString:@"#f5f5f5"];
    [self.view addSubview:self.codeLineLab];
    
    self.choseBtn = [ExpandButton buttonWithType:UIButtonTypeCustom];
    [self.choseBtn setImage:[UIImage imageNamed:@"login_chose"] forState:UIControlStateNormal];
    [self.choseBtn setImage:[UIImage imageNamed:@"login_chose_s"] forState:UIControlStateSelected];
    [self.choseBtn addTarget:self action:@selector(choseclick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.choseBtn];
    
    self.choseLab = [[YYLabel alloc]init];
    self.choseLab.font=[UIFont systemFontOfSize:13];
    self.choseLab.textColor = [UIColor colorWithHexString:@"#999999"];
    self.choseLab.numberOfLines = 0;
    self.choseLab.text = @"我已阅读并同意《隐私协议》，《用户协议》，《喵享家社区规则》";
    [self.view addSubview:self.choseLab];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(kNavBarHeight+3);
        make.left.offset(20);
        make.width.height.offset(18);
    }];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.backBtn.mas_bottom).offset(45);
        make.left.offset(53);
    }];
    [self.phoneIamgeV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLab.mas_bottom).offset(104);
        make.left.offset(50);
        make.width.height.offset(24);
    }];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.phoneIamgeV.mas_right).offset(8);
        make.right.offset(-16);
        make.height.offset(24);
        make.centerY.equalTo(self.phoneIamgeV.mas_centerY).offset(0);
    }];
    [self.phoneLineLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(22);
        make.right.offset(-16);
        make.top.equalTo(self.phoneIamgeV.mas_bottom).offset(11);
        make.height.offset(1);
    }];
    [self.codeIamgeV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneLineLab.mas_bottom).offset(36);
        make.left.offset(50);
        make.width.height.offset(24);
    }];
    [self.codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-16);
        make.height.offset(28);
        make.centerY.equalTo(self.codeIamgeV.mas_centerY).offset(0);
        make.width.offset(98);
    }];
    [self.codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.codeIamgeV.mas_right).offset(8);
        make.right.equalTo(self.codeBtn.mas_left).offset(-5);
        make.height.offset(24);
        make.centerY.equalTo(self.codeIamgeV.mas_centerY).offset(0);
    }];
    [self.codeLineLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(22);
        make.right.offset(-16);
        make.top.equalTo(self.codeIamgeV.mas_bottom).offset(11);
        make.height.offset(1);
    }];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(22);
        make.right.offset(-22);
        make.top.equalTo(self.codeLineLab.mas_bottom).offset(57);
        make.height.offset(43);
    }];
    [self.choseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-55);
        make.left.offset(20);
        make.width.height.offset(15);
    }];
    [self.choseLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.choseBtn.mas_right).offset(3);
        make.right.offset(-15);
        make.centerY.equalTo(self.choseBtn.mas_centerY).offset(0);
        make.height.offset(35);
    }];
    NSString *str = @"我已阅读并同意《隐私协议》，《用户协议》，《喵享家社区规则》";
    NSMutableAttributedString *titleText = [[NSMutableAttributedString alloc] initWithString:str];
    NSRange range1 = [str rangeOfString:@"《隐私协议》"];
    NSRange range2 = [str rangeOfString:@"《用户协议》"];
    NSRange range3 = [str rangeOfString:@"《喵享家社区规则》"];
    WEAKSELF
    [titleText setTextHighlightRange:range1 color:[UIColor colorWithHexString:@"#46A0FF"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf gotoWebWithUrl:@"https://www.maoxga.cn/yinsi.html" title:@"隐私协议"];
    }];
    [titleText setTextHighlightRange:range2 color:[UIColor colorWithHexString:@"#46A0FF"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf gotoWebWithUrl:@"https://www.maoxga.cn/xieyi.html" title:@"用户协议"];
    }];
    [titleText setTextHighlightRange:range3 color:[UIColor colorWithHexString:@"#46A0FF"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf gotoWebWithUrl:@"https://www.maoxga.cn/shequ.html" title:@"喵享家社区规则"];
    }];
    
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kScreenW, MAXFLOAT)];;
    YYTextLayout *titleTextLayout = [YYTextLayout layoutWithContainer:container text:titleText];
    self.choseLab.textLayout = titleTextLayout;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)gotoWebWithUrl:(NSString *)url title:(NSString *)title {
    DCWebViewController *webVc = [[DCWebViewController alloc] initWithUrl:url];
    webVc.titleString = title;
    [self.navigationController pushViewController:webVc animated:YES];
}


#pragma mark ----返回---
- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark ----获取验证码---
- (void)codeClick {
    if (self.phoneTF.text.length == 0) {
        [self.view xjmakeToast:@"请输入手机号码"];
        return;
    }
    self.codeBtn.userInteractionEnabled = NO;
    [self sendCode];
}

- (void)sendCode {
    MJWeakSelf
    NSDictionary *param = @{@"phone":self.phoneTF.text,
                            @"type":@"login"
    };
    [[DCHttpClient shareClient] requestWithPath:@"api/sendCode" params:param httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [weakSelf.view xjmakeToast:@"发送成功"];
            [weakSelf cutDown];
        } else {
            weakSelf.codeBtn.userInteractionEnabled = YES;
            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        weakSelf.codeBtn.userInteractionEnabled = YES;
    }];
}

- (void)textFieldDidChange:(UITextField *)textField {

    [self judgeBtnState];
}
//判断按钮状态
- (void)judgeBtnState {
    if (self.phoneTF.text.length >0 && self.codeTF.text.length >0) {
        self.loginBtn.backgroundColor = [UIColor colorWithHexString:@"#3378F7"];
        self.loginBtn.userInteractionEnabled = YES;
    } else {
        self.loginBtn.backgroundColor = [UIColor colorWithHexString:@"#E3E3E3"];
        self.loginBtn.userInteractionEnabled = NO;
    }

}
#pragma mark  -----勾选协议------
- (void)choseclick:(UIButton*)btn{
    btn.selected = ! btn.selected;
}
#pragma mark -----登录------
- (void)mobileLoginClick{
    if (!self.choseBtn.selected) {
        [self.view xjmakeToast:@"请勾选协议"];
        return;
    }
    self.loginBtn.userInteractionEnabled = NO;
    MJWeakSelf
    NSDictionary *param = @{@"phone":self.phoneTF.text,
                            @"captcha":self.codeTF.text,
                            @"registId":SAFEPARAMETER([AppDelegate shareDelegate].registrationID)
    };
    [[DCHttpClient shareClient] requestWithPath:@"api/loginByPhone" params:param httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            
            MXUserInfoModel *userInfo =  [MXUserInfoModel modelWithDictionary:dict[@"data"]];
            [DCObjectManager dc_saveUserData:userInfo.token forKey:DC_Token_Key];
            [DCCacheTool saveUserInfo:userInfo];
            UIWindow *window = [weakSelf getKeyWindow];
            window.rootViewController = [[DCNavigationController alloc] initWithRootViewController:[[DCTabbarController alloc] init]];
            [window makeKeyAndVisible];
        } else {
            weakSelf.loginBtn.userInteractionEnabled = YES;
            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        weakSelf.loginBtn.userInteractionEnabled = YES;
    }];
}

- (UIWindow *)getKeyWindow {
    
    UIWindow *keyWindow;
    if (@available(iOS 13.0, *)) {
        
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive) {
                
                keyWindow = windowScene.windows.firstObject;
                break;
            }
        }
    }
    return keyWindow;
}

- (void)cutDown {
    
    //开始倒计时
    __block NSInteger time = 59; //倒计时时间

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
       if(time <= 0){ //倒计时结束，关闭
           dispatch_source_cancel(self->_timer);
           dispatch_async(dispatch_get_main_queue(), ^{
               self.codeBtn.userInteractionEnabled = YES;
               [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
           });
       }else{
           int seconds = time % 60;
           dispatch_async(dispatch_get_main_queue(), ^{
               [self.codeBtn setTitle:[NSString stringWithFormat:@"%.2ds", seconds] forState:UIControlStateNormal];
           });
           time--;
       }
    });
    dispatch_resume(_timer);
}
@end
